<script>
import OAuthImg from "../../components/OAuthImg.vue";
import {ElMessage, ElNotification} from "element-plus";
import router from "../../router/index.js";
import request from "../../utils/Request.js";
import CryptoJS from "crypto-js"
import {Back} from "@element-plus/icons-vue";

export default {
  components: {Back, OAuthImg},
  data() {
    return {
      user: {
        email: '',
        password: '',
        passwordConfirm: '',
        code: '',
        checkTerms: false
      },
      // rules
      rules: {
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'change'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'},
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'change'},
          {type: 'number', message: '请输入正确的验证码', trigger: 'blur'},
        ],
        checkTerms: [{
          validator: (rule, value, callback) => {
            if (value)
              callback()
            else
              callback(new Error('请阅读并同意'))
          }, trigger: 'change'
        }],
        password: [{
          validator: (rule, value, callback) => {
            if (value === '')
              callback(new Error('请输入密码'))
            else if (!new RegExp("^[a-zA-Z0-9]{6,18}$").test(value))
              callback(new Error('请输入6到18位的不包括特殊字符的密码'))
            else
              callback()
          }, trigger: 'blur'
        }],
        passwordConfirm: [{
          validator: (rule, value, callback) => {
            if (value === '')
              callback(new Error('请再一次输入密码'))
            else if (value !== this.user.password)
              callback(new Error('两次输入的密码不一致'))
            else
              callback()
          }, trigger: 'blur'
        }]
      },
      // rules end
      //
      countDownValue: 0,
      isCountDown: false,
      disableCodeButton: false,
      disableRegButton: false
    }
  },
  methods: {
    onSubmit() {
      let form = this.$refs['formRef']
      console.log(this.user)
      form.validate((valid) => {
        if (valid) {
          this.disableRegButton = true
          //  注册
          request({
            method: 'post',
            url: '/api/uaa/reg',
            data: {
              email: this.user.email,
              // 密码进行加密
              password: CryptoJS.SHA256(this.user.password).toString(CryptoJS.enc.Hex),
              code: this.user.code
            }
          })
              .then(resp => {
                if (resp.data.code === 0) {
                  ElMessage.success('注册成功！\n正在跳转至登录页面')
                  router.replace({
                    path: '/login',
                    query: {
                      email: CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(this.user.email)),
                    }
                  });
                } else if (resp.data.code === 1302) {
                  ElNotification({
                    title: "验证码错误",
                    message: "请检查验证码是否填写正确",
                    type: "error",
                    duration: 0
                  })
                } else {
                  ElMessage.error(resp.data.msg)
                }
                this.disableRegButton = false
              })
              .catch(err => {
                console.log(err)
                ElMessage.error("出现未知错误！")
                this.disableRegButton = false
              })

        } else {
          ElMessage.error('请检查是否填写完整')
        }
      })

    },
    sendCode() {
      let form = this.$refs['formRef']
      form.validateField('email', (valid) => {
        if (valid) {
          if (!this.isCountDown) {
            this.disableCodeButton = true
            // 发送验证码
            // 邮箱Base64编码
            let emailEncoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(this.user.email))
            // console.log(CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(emailEncoded)))
            request({
              method: 'post',
              url: '/api/uaa/reg/code?email=' + emailEncoded,
            })
                .then(resp => {
                  let data = resp.data
                  if (data.code === 0) {
                    // 发送成功
                    ElMessage.success("发送验证码成功！")
                    this.isCountDown = true;
                    this.countDownValue = Date.now() + 60000
                  } else if (data.code === 1204) {
                    ElMessage.error('请勿频繁发送验证码！')
                    this.isCountDown = true;
                    this.countDownValue = Date.now() + 60000
                  } else {
                    ElMessage.error(data.msg)
                  }
                  this.disableCodeButton = false
                })
                .catch(err => {
                  console.log(err)
                  if (!this.isCountDown)
                    ElMessage.error('发送验证码失败！')
                  this.disableCodeButton = false
                })

          } else {
            ElMessage.error('请勿频繁发送验证码！')
          }
        }
      })
    }
  },
  created() {
    document.title = '注册 | 柿子文档'
  }
}
</script>

<template>
  <el-icon @click="() => this.$router.back()" size="30" style="cursor: pointer">
    <Back/>
  </el-icon>

  <div class="outer">
    <h1 class="w-300 text-center">
      <router-link class="a-style mb-5" to="/" style="color: #4d4d4d">注册</router-link>
    </h1>

    <!--    FORM-->
    <el-form
        ref="formRef"
        :model="user"
        status-icon
        :rules="rules"
    >
      <el-form-item prop="email" key="email">
        <el-input class="w-300 mb-5" size="large" v-model="user.email" placeholder="邮箱" clearable
                  maxlength="64"/>
      </el-form-item>

      <el-form-item prop="password" key="password">
        <el-input class="w-300 mb-5" size="large" v-model="user.password" placeholder="密码" type="password"
                  show-password
                  clearable maxlength="64"/>
      </el-form-item>
      <el-form-item prop="passwordConfirm" key="passwordConfirm">
        <el-input class="w-300 mb-5" size="large" v-model="user.passwordConfirm" placeholder="再输入密码"
                  type="password"
                  show-password
                  clearable maxlength="64"/>
      </el-form-item>
      <el-form-item prop="code" key="code">
        <el-input class="w-300 mb-5" size="large" v-model.number="user.code" placeholder="验证码"
                  type="number"
                  maxlength="6">
          <template #append>
            <el-button @click="sendCode" :disabled="isCountDown || disableCodeButton"
            >
              <span v-show="!isCountDown" class="w-50">
              发送
              </span>
              <el-countdown
                  v-show="isCountDown"
                  format="ss"
                  :value="countDownValue"
                  @finish="() => this.isCountDown = false"
                  class="w-50"
                  :value-style="{ fontSize: '17px', color: 'gray' }"
              />
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="checkTerms" key="checkTerms">
        <el-checkbox class="w-300 font-style" v-model="user.checkTerms">
          已阅读并同意
          <router-link to="/term/service" class="a-style">服务条款</router-link>
          和
          <router-link to="/term/privacy" class="a-style">隐私协议</router-link>
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button class="w-300" type="primary" @click="onSubmit" size="large"
                   color="#ff9800" dark
        >注册
        </el-button>
      </el-form-item>
    </el-form>

    <!--    FORM END-->

    <p class="w-300 text-center font-style">已有账号？
      <router-link class="a-style" to="/login">前往登录</router-link>
    </p>
    <OAuthImg/>
  </div>
</template>

<style scoped>

.outer {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.font-style {
  font-size: 14px;
  color: #737679;
}

.a-style {
  text-decoration: none;
  color: cornflowerblue;
}

</style>